let audio;
let queue = [];
const AUDIO_BASE_URL = '/static/plugins/netcall/audio/';
const audioMap = {
  A: 'avchat_connecting', // 正在呼叫
  B: 'avchat_no_response', // 无人接听
  C: 'avchat_peer_busy', // 对方通话中
  D: 'avchat_peer_reject', // 拒绝
  E: 'avchat_ring' // 响铃
};

const audioURLFactory = (type) => {
  const audioName = audioMap[type];
  return `${AUDIO_BASE_URL + audioName}.mp3`;
};

const scheduleQueue = (task) => {
  queue.push(task);
};

const shiftQueue = () => {
  queue.shift();
};

const clearQueue = () => {
  queue = [];
};

const createAudio = (url) => {
  let audio = document.createElement('audio');
  audio.autoplay = true;
  audio.src = url;

  return audio;
};

const stopRing = () => {
  clearQueue();

  if (audio) {
    audio.pause();
    audio = null;
  }
};

const scheduleConnectingQueue = () => {
  const connectingURL = audioURLFactory('A');
  const ringURL = audioURLFactory('E');

  scheduleQueue({ url: connectingURL, count: 1 });
  scheduleQueue({ url: ringURL, count: 10000 });
};

const scheduleNoResponseQueue = () => {
  const noResponseURL = audioURLFactory('B');

  scheduleQueue({ url: noResponseURL, count: 2 });
};

const scheduleRejectQueue = () => {
  const rejectURL = audioURLFactory('D');

  scheduleQueue({ url: rejectURL, count: 2 });
};

const scheduleBusyQueue = () => {
  const busyURL = audioURLFactory('C');

  scheduleQueue({ url: busyURL, count: 2 });
};

const playSingleRing = () => {
  return new Promise((resolve, reject) => {
    const ring = queue[0];

    if (!ring || !ring.count) {
      shiftQueue();
      stopRing();
      resolve();
      return;
    }

    audio = createAudio(ring.url);
    audio.addEventListener('ended', () => {
      resolve();
    });

    ring.count = ring.count - 1;

    if (ring.count <= 0) {
      shiftQueue();
    }
  });
};

const playRing = async (callback) => {
  while (queue.length) {
    await playSingleRing();
  }

  if (typeof callback === 'function') {
    callback();
  }
};

const playConnectingRing = (cb) => {
  stopRing();
  scheduleConnectingQueue();
  playRing(cb);
};

const playRejectRing = (cb) => {
  stopRing();
  scheduleRejectQueue();
  playRing(cb);
};

const playBusyRing = (cb) => {
  stopRing();
  scheduleBusyQueue();
  playRing(cb);
};

const playNoResponseRing = (cb) => {
  stopRing();
  scheduleNoResponseQueue();
  playRing(cb);
};

export default {
  stopRing,
  playConnectingRing,
  playRejectRing,
  playBusyRing,
  playNoResponseRing
};
